package com.atguigu.gmall.pay.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePageMergePayModel;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.request.*;
import com.alipay.api.response.AlipayTradeCloseResponse;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.order.feign.OrderFeign;
import com.atguigu.gmall.pay.service.AliPayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@Service
public class AliPayServiceImpl implements AliPayService {
    @Autowired
    private OrderFeign orderFeign;

    @Value("${alipay_url}")
    private String alipay_url;

    @Value("${app_id}")
    private String app_id;

    @Value("${app_private_key}")
    private String app_private_key;

    @Value("${alipay_public_key}")
    private String alipay_public_key;

    @Value("${return_payment_url}")
    private String return_payment_url;

    @Value("${notify_payment_url}")
    private String notify_payment_url;

    /**
     * 支付宝下单
     *
     * @param orderId
     * @return
     */
    @Override
    public String aliPay(Long orderId) {
        //查询订单的详细信息
        OrderInfo orderInfo = orderFeign.getById(orderId);
        //获取订单的金额
        BigDecimal totalAmount = orderInfo.getTotalAmount();
        //包装支付参数
        AlipayClient alipayClient =
                new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
                        app_id,
                        app_private_key,
                        "json",
                        "utf-8",
                        alipay_public_key,
                        "RSA2");
        //声明请求体
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();

        try {
            //设置请求参数
            request.setReturnUrl(return_payment_url);
            request.setNotifyUrl(notify_payment_url);
            //封装bizContent
            HashMap<String, String> bizMap = new HashMap<>();
            bizMap.put("out_trade_no",orderId+"");
            bizMap.put("product_code","FAST_INSTANT_TRADE_PAY");
            bizMap.put("total_amount",totalAmount.doubleValue()+"");
            bizMap.put("subject","java0107支付宝支付测试");
            request.setBizContent(JSONObject.toJSONString(bizMap));
            //发起请求
            AlipayTradePagePayResponse response = alipayClient.pageExecute(request);
            //解析结果
            if (response.isSuccess()){
                return response.getBody();
            }else{
                return null;
            }
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 校验阿里支付的结果:主动查询
     *
     * @param orderId
     * @return
     */
    @Override
    public String checkAliPay(Long orderId) {
        //包装支付参数
        AlipayClient alipayClient =
                new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
                        app_id,
                        app_private_key,
                        "json",
                        "utf-8",
                        alipay_public_key,
                        "RSA2");
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        try {
            //封装bizContent
            Map<String,String> bizMap = new HashMap<>();
            bizMap.put("out_trade_no",orderId+"");
            request.setBizContent(JSONObject.toJSONString(bizMap));
            AlipayTradeQueryResponse response = alipayClient.execute(request);
            if (response.isSuccess()){
                return response.getBody();
            }else {
                return null;
            }
        }catch (Exception e){
            e.getLocalizedMessage();
            return null;
        }
    }

    /**
     * 关闭订单
     *
     * @param orderId
     * @return
     * @throws Exception
     */
    @Override
    public String close(Long orderId) throws Exception {
        AlipayClient alipayClient =
                new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
                        app_id,
                        app_private_key,
                        "json",
                        "utf-8",
                        alipay_public_key,
                        "RSA2");
        AlipayTradeCloseRequest request = new AlipayTradeCloseRequest();
        Map<String,String> bizMap = new HashMap<>();
        bizMap.put("out_trade_no",orderId+"");
        request.setBizContent(JSONObject.toJSONString(bizMap));
        AlipayTradeCloseResponse response = alipayClient.execute(request);
        if (response.isSuccess()){
            return response.getBody();
        }else {
            return null;
        }
    }

    /**
     * 退款
     *
     * @param orderId
     * @return
     * @throws Exception
     */
    @Override
    public String refund(Long orderId) throws Exception {
        AlipayClient alipayClient =
                new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
                        app_id,
                        app_private_key,
                        "json",
                        "utf-8",
                        alipay_public_key,
                        "RSA2");
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        Map<String, String> bizMap = new HashMap<>();
        bizMap.put("out_trade_no", orderId + "");
        bizMap.put("refund_amount","0.01");
        bizMap.put("refund_reason", "莫名奇妙的退款");
        request.setBizContent(JSONObject.toJSONString(bizMap));
        AlipayTradeRefundResponse response = alipayClient.execute(request);
        if(response.isSuccess()){
            return response.getBody();
        }else {
            return  null;
        }

    }
}
